package vn.edu.ptithcm.pim.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ParameterizableViewController;

import vn.edu.ptithcm.pim.constant.Constants;
import vn.edu.ptithcm.pim.constant.UrlConstants;
import vn.edu.ptithcm.pim.dom.Customer;
import vn.edu.ptithcm.pim.service.CustomerService;
import vn.edu.ptithcm.pim.service.UserService;
import vn.edu.ptithcm.pim.util.ParamUtil;

public class ShowCustomerDetailController extends ParameterizableViewController {
	private UserService userService;
	private CustomerService customerService;

	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		long id = ParamUtil.getLong(request, "id", 0);
		Map<String, Object> bean = new HashMap<String, Object>();
		if (userService.isSignedIn(request)) {
			String loginName = userService.getCurrentLogin(request);
			bean.put("isSigned", true);
			bean.put(Constants.LOGIN_NAME, loginName);
			bean.put(Constants.USER_NAME, userService.getUsername(loginName));
			bean.put("isAdmin", userService.isAdmin(loginName));
			bean.put("id", id);
			Customer customer = customerService.findById(id);
			bean.put("customer", customer);
		} else {
			String redirectLink = UrlConstants.CUSTOMERS_DETAIL_URL
					+ UrlConstants.HTM;
			request.getSession().setAttribute("redirectLink", redirectLink);
			response.sendRedirect(UrlConstants.HOME_PAGE_URL + UrlConstants.HTM);
		}
		return new ModelAndView(UrlConstants.CUSTOMERS_DETAIL_URL, "bean", bean);
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public CustomerService getCustomerService() {
		return customerService;
	}

	public void setCustomerService(CustomerService customerService) {
		this.customerService = customerService;
	}

}
